import datetime
import re
import pprint
from utils.time_util import YYYYMMDDHHMM, current_time, timestamp2str
from worker.article_worker import ArticleWorker
from constant.globl_constant import titleDict


class MT5Worker(ArticleWorker):
    """
    MT5交易信号
    """

    timeSpace = 10 * 60
    lastTime = -1

    def __init__(self):
        super().__init__(justTitle=True, sleepTime=self.timeSpace, login=False)

    def timeCheck(self):
        """
        时间检查
        """

        if self.lastTime == -1:
            self.updateRecord()
            self.sqlite.delete_record("DELETE FROM article_table")
            self.lastTime = current_time()
        return True

    def mt5CallBack(self):
        """
        MT5方法实现
        """

        articleInfo = self.sqlite.query_many(
            "SELECT title,time FROM article_table WHERE title != ''")

        if articleInfo != None and len(articleInfo) != 0:
            priceList = {}
            titleStr = {}

            sortedList = sorted(articleInfo, key=lambda x: x[1], reverse=True)

            for value in sortedList:
                childResult = re.findall("\d{4}", value[0], re.S)
                if len(childResult) != 0 and childResult != None:
                    try:
                        yearValue = datetime.datetime.now().year
                        childValue = [
                            item for item in childResult
                            if item != str(yearValue)
                        ]
                        if len(childValue) != 0:
                            numValue = childValue[0]
                            priceList[value[1]] = int(numValue)
                            titleStr[value[1]] = value[0]
                    except Exception as e:
                        print("标题解析失败:" + str(e))

            if len(priceList) != 0 and len(titleStr) != 0:
                reList = {
                    timestamp2str(k, YYYYMMDDHHMM): priceList[k]
                    for k in sorted(priceList, reverse=True)
                }
                titleList = {
                    timestamp2str(k, YYYYMMDDHHMM): titleStr[k]
                    for k in sorted(titleStr, reverse=True)
                }

                titleDict["a"] = reList
                titleDict["b"] = titleList

                print("\n\n\n\n\n" +
                      timestamp2str(current_time(), YYYYMMDDHHMM))
                pprint.pprint(reList, sort_dicts=False)
                print("\n\n\n\n\n" +
                      timestamp2str(current_time(), YYYYMMDDHHMM))
                pprint.pprint(titleList, sort_dicts=False)
